import React, { useEffect, useState, useImperativeHandle, forwardRef, useRef } from 'react';
import { Table, Button, Space, Pagination, Tag, Tooltip, message, Modal, Form, Input } from 'antd';
import { EyeOutlined, EditOutlined, ShareAltOutlined, StarOutlined, StarFilled, StopOutlined, LinkOutlined } from '@ant-design/icons';
import { getSearchDocArchiveList, getContentByFileId, getDocArchiveById, getSharedDocArchiveList, getPersonalDocArchiveList, getFollowedArchiveList, shareDocArchive, unshareDocArchive, followArchive, unfollowArchive, createDocArchive, updateDocArchive } from "@/apis/front/docArchive"
import { getUserList } from '../../../apis/front/document';
import UploadAttachment from '../../../components/upload/UploadAttachment';
import RichEditor, { RichEditorRef } from '@/components/editor/editor';
import { Editor_Default_Directory } from '@/globals/document';
import { downloadFileById } from '@/apis/backhub/directory';
import { converHtml2Word } from '@/apis/public/fileUpDownload';
import styles from './docArchive.module.css';

const { Search } = Input;
// mock 当前用户id
const currentUserId = window.HubUser?.id;

interface DocArchive {
	title?: string;
	writingType?: string;
	content?: string;
}

const DocArchiveTable = (props: { type: string }, ref) => {
	const editorRef = useRef<RichEditorRef>(null);
	const [data, setData] = useState([]);
	const [mode, setMode] = useState(false);
	const [keyWord, setKeyWord] = useState('');
	const [billid, setBillid] = useState(0);
	const [addVisible, setAddVisible] = useState(false);
	const [viewVisible, setViewVisible] = useState(false);
	const [viewDataInfo, setViewDataInfo] = useState<DocArchive>({})
	const [fileContent, setFileContent] = useState('');
	const [editVisible, setEditVisible] = useState(false);
	const [userObj, setUserObj] = useState({});
	const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
	const [formAdd] = Form.useForm();
	const [formEdit] = Form.useForm();
	useEffect(() => {
		fetchUserData()
	}, [])
	useImperativeHandle(ref, () => ({
		showModal
	})
	);

	const showModal = () => {
		setAddVisible(true)
	}
	const fetchUserData = async () => {
		const treeRes = await getUserList()
		if (treeRes.status) {
			const userInfo = {}
			treeRes.data.map(item => {
				userInfo[`${item.id}`] = item.name
			})
			setUserObj(userInfo)
		}
	}

	useEffect(() => {
		fetchData();
	}, [props.type, pagination.current]);

	const fetchData = async () => {
		if (mode) {
			onSearch(keyWord);
			return;
		}
		const all = [];
		let total = 0;
		if (props.type === "system") {
			const followedRes = await getFollowedArchiveList(1, 10000);
			const followIds = [];
			if (followedRes.status) {
				followedRes.data.page.records.map(item => {
					followIds.push(item.id)
				})
			}
			const res = await getSharedDocArchiveList(pagination.current, pagination.pageSize);
			if (res.status) {
				total = res.data.total
				res.data.page.records.map(item => {
					all.push({
						id: item.id,
						title: item.title,
						type: item.writingType,
						provider: userObj[`${item.userId}`],
						providerId: item.userId,
						createdAt: item.createTime ? item.createTime.substring(0, 10) : '',
						isFavorite: followIds.includes(item.id) ? true : false,
						isShared: item.isShared === 1 ? true : false
					})
				})
			}
		} else if (props.type === "personal") {
			const followedRes = await getFollowedArchiveList(1, 10000);
			const followIds = [];
			if (followedRes.status) {
				followedRes.data.page.records.map(item => {
					followIds.push(item.id)
				})
			}
			const res = await getPersonalDocArchiveList(pagination.current, pagination.pageSize);
			total = res.data.total
			res.data.page.records.map(item => {
				all.push({
					id: item.id,
					title: item.title,
					type: item.writingType,
					provider: userObj[`${item.userId}`],
					providerId: item.userId,
					createdAt: item.createTime ? item.createTime.substring(0, 10) : '',
					isFavorite: followIds.includes(item.id) ? true : false,
					isShared: item.isShared === 1 ? true : false
				})
			})
		} else if (props.type === "favorite") {
			const res = await getFollowedArchiveList(pagination.current, pagination.pageSize);
			total = res.data.total
			res.data.page.records.map(item => {
				all.push({
					id: item.id,
					title: item.title,
					type: item.writingType,
					provider: userObj[`${item.userId}`],
					providerId: item.userId,
					createdAt: item.createTime ? item.createTime.substring(0, 10) : '',
					isFavorite: true,
					isShared: item.isShared === 1 ? true : false
				})
			})
		}
		setData(all.slice((pagination.current - 1) * pagination.pageSize, pagination.current * pagination.pageSize));
		setPagination(prev => ({ ...prev, total: total }));
	};

	// 操作按钮事件（仅做提示）
	const handleAction = async (action: string, record: any) => {
		if (action === "查看") {
			const res = await getDocArchiveById(record.id)
			if (res.status && res.data.success) {
				setViewDataInfo({
					title: res.data.data?.title,
					writingType: res.data.data?.writingType,
					content: res.data.data?.content
				})
				setViewVisible(true);
			} else {
				message.error("数据不存在")
			}
		} else if (action === "编辑") {
			setBillid(record.id)
			const res = await getDocArchiveById(record.id)
			if (res.status) {
				formEdit.setFieldsValue({
					title: res.data.data?.title,
					writingType: res.data.data?.writingType,
					content: res.data.data?.content
				})
				setEditVisible(true);
			} else {
				message.error("数据查询异常")
			}
		} else if (action === "分享") {
			const res = await shareDocArchive(record.id)
			if (res.status) {
				fetchData();
				message.success("分享成功")
			} else {
				message.error("操作异常")
			}
		} else if (action === "取消分享") {
			const res = await unshareDocArchive(record.id)
			if (res.status) {
				fetchData();
				message.success("取消分享成功")
			} else {
				message.error("操作异常")
			}
		} else if (action === "收藏") {
			const res = await followArchive(record.id);
			if (res.status) {
				fetchData();
				message.success("收藏成功")
			} else {
				message.error("操作异常")
			}
		} else if (action === "取消收藏") {
			const res = await unfollowArchive(record.id);
			if (res.status) {
				fetchData();
				message.success("取消收藏成功")
			} else {
				message.error("操作异常")
			}
		}
	};

	// 不同tab的表头和操作
	let columns: any[] = [];
	if (props.type === 'system') {
		columns = [
			{ title: '文件标题', dataIndex: 'title', key: 'title' },
			{ title: '文件类型', dataIndex: 'type', key: 'type', render: t => <Tag color="blue">{t}</Tag> },
			{ title: '提供者', dataIndex: 'provider', key: 'provider' },
			{ title: '创建日期', dataIndex: 'createdAt', key: 'createdAt' },
			{
				title: '操作',
				key: 'action',
				render: (_: any, record: any) => (
					<Space>
						<Tooltip title="查看"><Button size="small" icon={<EyeOutlined />} onClick={() => handleAction('查看', record)} /></Tooltip>
						{record.providerId === currentUserId && (
							<Tooltip title="编辑"><Button size="small" icon={<EditOutlined />} onClick={() => handleAction('编辑', record)} /></Tooltip>
						)}
						{record.providerId === currentUserId && (
							<Tooltip title="取消分享"><Button size="small" danger icon={<StopOutlined />} onClick={() => handleAction('取消分享', record)} /></Tooltip>
						)}
						{!record.isFavorite && (
							<Tooltip title="收藏"><Button size="small" icon={<StarOutlined />} onClick={() => handleAction('收藏', record)} /></Tooltip>
						)}
						{record.isFavorite && (
							<Tooltip title="取消收藏"><Button size="small" icon={<StarFilled />} onClick={() => handleAction('取消收藏', record)} /></Tooltip>
						)}
					</Space>
				)
			}
		];
	} else if (props.type === 'personal') {
		columns = [
			{ title: '文件标题', dataIndex: 'title', key: 'title' },
			{ title: '文件类型', dataIndex: 'type', key: 'type', render: t => <Tag color="green">{t}</Tag> },
			{ title: '创建日期', dataIndex: 'createdAt', key: 'createdAt' },
			{ title: '是否已分享', dataIndex: 'isShared', key: 'isShared', render: v => v ? <Tag color="blue">已分享</Tag> : <Tag>未分享</Tag> },
			{
				title: '操作',
				key: 'action',
				render: (_: any, record: any) => (
					<Space>
						<Tooltip title="查看"><Button size="small" icon={<EyeOutlined />} onClick={() => handleAction('查看', record)} /></Tooltip>
						<Tooltip title="编辑"><Button size="small" icon={<EditOutlined />} onClick={() => handleAction('编辑', record)} /></Tooltip>
						{!record.isShared && (
							<Tooltip title="分享"><Button size="small" icon={<ShareAltOutlined />} onClick={() => handleAction('分享', record)} /></Tooltip>
						)}
						{record.isShared && (
							<Tooltip title="取消分享"><Button size="small" danger icon={<StopOutlined />} onClick={() => handleAction('取消分享', record)} /></Tooltip>
						)}
					</Space>
				)
			}
		];
	} else if (props.type === 'favorite') {
		columns = [
			{ title: '文件标题', dataIndex: 'title', key: 'title' },
			{ title: '文件类型', dataIndex: 'type', key: 'type', render: t => <Tag color="purple">{t}</Tag> },
			{ title: '创建日期', dataIndex: 'createdAt', key: 'createdAt' },
			{
				title: '操作',
				key: 'action',
				render: (_: any, record: any) => (
					<Space>
						<Tooltip title="查看"><Button size="small" icon={<EyeOutlined />} onClick={() => handleAction('查看', record)} /></Tooltip>
						<Tooltip title="取消收藏"><Button size="small" icon={<StarFilled />} onClick={() => handleAction('取消收藏', record)} /></Tooltip>
					</Space>
				)
			}
		];
	}
	const locale = {
		emptyText: '暂无数据',
	}
	const handleAddCancel = () => {
		setAddVisible(false);
	}
	const handleViewCancel = () => {
		setViewVisible(false)
	}
	const handleEditCancel = () => {
		setEditVisible(false)
	}
	const handleSave = () => {
		formAdd.validateFields().then(async source => {
			const res = await createDocArchive({ userId: currentUserId, title: source.title, content: fileContent, writingType: source.writingType, writingRecordId: 1 })
			if (res.status) {
				message.success("保存成功")
				setAddVisible(false)
				fetchData()
			} else {
				message.success("保存异常")
			}
		})

	}

	const handleEditSave = () => {
		formEdit.validateFields().then(async source => {
			const res = await updateDocArchive({ id: billid, userId: currentUserId, title: source.title, content: fileContent, writingType: source.writingType, writingRecordId: 1 })
			if (res.status) {
				message.success("保存成功")
				setEditVisible(false)
				fetchData()
			} else {
				message.success("保存异常")
			}
		})
	}
	interface FileRresponse {
		code: number;
		msg: string;
		status: boolean;
		data: any;
		fail: boolean;
	}
	const handleUploadSuccess = async (resp: FileRresponse) => {
		if (resp.data.status) {
			if (resp.data.data.page.length > 0) {
				const contentRes = await getContentByFileId({ id: resp.data.data.page[0].id })
				if (contentRes.status && contentRes.data.success) {
					setFileContent(contentRes.data.content)
					formAdd.setFieldsValue({
						file: contentRes.data.content
					})
					formEdit.setFieldsValue({
						file: contentRes.data.content
					})
				}
			} else {
				message.error("文件上传异常")
			}

		} else {
			message.error("文件上传异常")
		}
	}
	const handleExport = async () => {
		try {
			const editor = editorRef?.current?.getEditor();
			if (!editor) {
				message.error('获取编辑器实例失败');
				return;
			}
			const fileName = viewDataInfo?.title ? viewDataInfo?.title + '.docx' : '正文.docx';
			const res = await converHtml2Word({ html: editor.getHtml(), fileName, directoryId: Editor_Default_Directory })
			if (res.status) {
				await downloadFileById(res.data.id, fileName)
			}
		} finally {
		}
	}
	const handleEditorChange = (content: string) => {
		setViewDataInfo(pre => ({ ...pre, content }))
	};
	const onSearch = async (value) => {
		setKeyWord(value);
		if (value === "") {
			setPagination({ current: 1, pageSize: 10, total: 0 })
			fetchData()
			setMode(false)
			return;
		}
		if (!mode) {
			setPagination({ current: 1, pageSize: 10, total: 0 })
		}
		setMode(true)
		const followedRes = await getFollowedArchiveList(1, 10000);
		const followIds = [];
		if (followedRes.status) {
			followedRes.data.page.records.map(item => {
				followIds.push(item.id)
			})
		}
		const type = props.type === "system" ? 1 : props.type === "personal" ? 2 : props.type === "favorite" ? 3 : 1
		const res = await getSearchDocArchiveList(pagination.current, pagination.pageSize, value, type);
		let total = 0;
		const all = []
		if (res.status) {
			total = res.data.total
			res.data.page.records.map(item => {
				all.push({
					id: item.id,
					title: item.title,
					type: item.writingType,
					provider: userObj[`${item.userId}`],
					providerId: item.userId,
					createdAt: item.createTime ? item.createTime.substring(0, 10) : '',
					isFavorite: followIds.includes(item.id) ? true : false,
					isShared: item.isShared === 1 ? true : false
				})
			})
			setData(all.slice((pagination.current - 1) * pagination.pageSize, pagination.current * pagination.pageSize));
			setPagination(prev => ({ ...prev, total: total }));
		}
	}
	return (
		<div style={{ background: '#fff', borderRadius: 8, boxShadow: '0 2px 8px #e6e6e6', padding: 16 }}>
			<div className={styles.searchBar}>
				<Search
					placeholder="请输入关键词"
					allowClear
					enterButton="搜索"
					size="large"
					onSearch={onSearch}
				/>
			</div>
			<Table
				columns={columns}
				dataSource={data}
				rowKey="id"
				pagination={false}
				bordered
				locale={locale}
				size="middle"
				style={{ minHeight: 240 }}
			/>
			<Pagination
				{...pagination}
				align="end"
				onChange={page => setPagination(p => ({ ...p, current: page }))}
				style={{ marginTop: 16, textAlign: 'right' }}
			/>
			<Modal
				title="新增知识"
				visible={addVisible}
				onCancel={handleAddCancel}
				width={'60%'}
				footer={null}
			>
				<Form
					form={formAdd}
					layout="vertical"
					onFinish={handleSave}
				>
					<Form.Item
						label="标题"
						name="title"
						rules={[{ required: true, message: '请输入标题' }]}
					>
						<Input placeholder="请输入标题" />
					</Form.Item>
					<Form.Item
						label="类型"
						name="writingType"
						rules={[{ required: true, message: '请输入类型' }]}
					>
						<Input placeholder="请输入类型" />
					</Form.Item>
					<Form.Item
						label="选择文件"
						name="file"
						rules={[{ required: true, message: '请输入选择文档' }]}
					>
						<UploadAttachment
							directory={Editor_Default_Directory}
							maxFileSize={5 * 1024 * 1024} // 限制文件大小为 5MB
							onUploadSuccess={handleUploadSuccess}
							child={<LinkOutlined />}
						/>
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							保存
						</Button>
					</Form.Item>
				</Form>
			</Modal>
			<Modal
				title="查看知识"
				visible={viewVisible}
				onCancel={handleViewCancel}
				width={'60%'}
				footer={null}
			>
				<div className={styles.editTitle}>
					<text>{viewDataInfo?.title}</text>
				</div>
				<div className={styles.editSubTitle}>
					<text>{viewDataInfo?.writingType}</text>
				</div>
				<RichEditor
					ref={editorRef}
					value={viewDataInfo?.content}
					onChange={handleEditorChange}
					readOnly={true} // 当处理中时禁用编辑器
					onExport={handleExport}
				/>
			</Modal>
			<Modal
				title="编辑知识"
				visible={editVisible}
				onCancel={handleEditCancel}
				width={'60%'}
				footer={null}
			>
				<Form
					form={formEdit}
					layout="vertical"
					onFinish={handleEditSave}
				>
					<Form.Item
						label="标题"
						name="title"
						rules={[{ required: true, message: '请输入标题' }]}
					>
						<Input placeholder="请输入标题" />
					</Form.Item>
					<Form.Item
						label="类型"
						name="writingType"
						rules={[{ required: true, message: '请输入类型' }]}
					>
						<Input placeholder="请输入类型" />
					</Form.Item>
					<Form.Item
						label="选择文件"
						name="file"
						rules={[{ required: true, message: '请输入选择文档' }]}
					>
						<UploadAttachment
							directory={Editor_Default_Directory}
							maxFileSize={5 * 1024 * 1024} // 限制文件大小为 5MB
							onUploadSuccess={handleUploadSuccess}
							child={<LinkOutlined />}
						/>
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							保存
						</Button>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
};

export default forwardRef(DocArchiveTable);
